package com.qianfeng.smartdevices.websocket.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.HashMap;
import java.util.Map;

//@Component
public class MyChatHandler extends TextWebSocketHandler {
    private Map<Object, WebSocketSession> allClients = new HashMap<>();

    private ObjectMapper objectMapper;
    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.err.println("用户和服务器建立websocket请求了");
        Object name = session.getAttributes().get("name");
        allClients.put(name,session);
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.err.println("收到客户端发来的消息" + payload);

        Map map = objectMapper.readValue(payload, Map.class);

        Object toUser = map.get("toUser");
        WebSocketSession socketSession = allClients.get(toUser);

        if (socketSession != null && socketSession.isOpen()) {
            Object from = session.getAttributes().get("name");
            socketSession.sendMessage(new TextMessage("收到了来自于"+from+"的消息，内容是"+map.get("msg")));
        }else {
            session.sendMessage(new TextMessage("对方不在线"));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
    }
}
